<?php
namespace Admin\Controller;

use Think\Controller;

class MemberController extends RightController
{
    // 加载初始化内容页,并检索
    public function index()
    {
        //判断分页时搜索条件
        if (I("get.p")) {
            $where = session("QG_SEARCH_WHERE_member");
            $this->assign("params", session("QG_SEARCH_PARAMS_member"));
            $where = empty($where) ? "1" : $where;
            $pageSize = session("QG_SEARCH_SIZE_member");
        } else {
            //清除session存储
            session("QG_SEARCH_WHERE_member", null);
            session("QG_SEARCH_PARAMS_member", null);
            session("QG_SEARCH_SIZE_member", null);
            $pageSize = I("post.pageSize");

            $where = "1";
        }

        // POST数据提交，重新组合检索条件
        if (IS_POST) {
            unset($_GET["p"]);
            $where = $this->searchCondition();
        }
//        print_r($where);die;
        // 分页输入
        if (empty($pageSize)) {
            $pageSize = 10;
        }

        $where .= " AND isDelete=2 ";

        // 总条数
        $count = M('member')
            ->alias("t")
            ->where($where)
            ->count();
        $page = new \Admin\Model\Page($count, $pageSize);
        $show = $page->show();

        // 进行分页数据查询
        $list = M('member')
            ->alias("t")
            ->where($where)
            ->order('t.id desc')
            ->limit($page->firstRow . ',' . $page->listRows)->select();

        // 统计
        $sum = M('member')
            ->alias("t")
            ->field("count(1) as countNum")
            ->where($where)
            ->order('t.id DESC')
            ->find();

        // 渲染查询条件到session
        session("QG_SEARCH_WHERE_member", $where);
        session("QG_SEARCH_PARAMS_member", I("post."));
        session("QG_SEARCH_SIZE_member", $pageSize);

        // 输出数据
        $this->assign("params", I("post."));
        $this->assign('list', $list);
        $this->assign('sum', $sum);
        $this->assign('lists', array(
            "page" => getDropdownList("pageSize", "", false),
            "isDisable" => getDropdownList("isDisable")
        ));
        $this->assign('page', $show);
        $this->display();
    }

    // 搜索条件
    public function searchCondition()
    {
        $where = "1";

        // 创建时间
        if (I('post.createtimeStart') || I('post.createtimeEnd')) {
            // 起始日期
            if (I('post.createtimeStart')) {
                $where .= " AND t.createTime>='" . I("post.createtimeStart") . "'";
            }
            // 结束日期
            if (I('post.createtimeEnd')) {
                $where .= " AND t.createTime<='" . I("post.createtimeEnd") . " 23:59:59'";
            }
        }

        // 更新时间
        if (I('post.updatetimeStart') || I('post.updatetimeEnd')) {
            // 起始日期
            if (I('post.updatetimeStart')) {
                $where .= " AND t.updateTime>='" . I("post.updatetimeStart") . "'";
            }
            // 结束日期
            if (I('post.updatetimeEnd')) {
                $where .= " AND t.updateTime<='" . I("post.updatetimeEnd") . " 23:59:59'";
            }
        }

        // 姓名
        if (I('post.nickname')) {
            // 精确
            if (I('post.nicknameCondition') == 1) {
                $where .= " AND t.nickname='" . I("post.nickname") . "'";
            } else {
                $where .= " AND t.nickname LIKE '%" . I("post.nickname") . "%'";
            }
        }

        // 账号
        if (I('post.account')) {
            // 精确
            if (I('post.accountCondition') == 1) {
                $where .= " AND t.account='" . I("post.account") . "'";
            } else {
                $where .= " AND t.account LIKE '%" . I("post.account") . "%'";
            }
        }

        // 推荐人账户
        if (I('post.parentaccount')) {
            // 精确
            if (I('post.parentaccountCondition') == 1) {
                $where .= " AND t.parentAccount='" . I("post.parentaccount") . "'";
            } else {
                $where .= " AND t.parentAccount LIKE '%" . I("post.parentaccount") . "%'";
            }
        }

        // 是否禁用
        if (I('post.isdisable')) {
            $where .= " AND t.isDisable='" . I("post.isdisable") . "'";
        }

        $where .= " AND t.isDelete='2'";
        return $where;
    }

    // 添加会员
    public function add()
    {
        if (IS_POST) {
            // 数据
            $data = array();

            // 姓名
            $data['nickname'] = I('post.nickname');

            // 账号
            $data['account'] = I('post.account');

            if (I('post.password') && I('post.password') != "") {
                // 密码
                $data['password'] = md5(trim(I('post.password')));
            }
            if (I('post.paypassword') && I('post.paypassword') != "") {
                // 支付密码
                $data['paypassword'] = md5(trim(I('post.paypassword')));
            }
            $member=M("member")->where(array("acount"=>I('post.parentaccount')))->find();
            if(!empty($member)){
                $data['parentId'] = $member['id'];
            }
            // 推荐人账户
            $data['parentAccount'] = I('post.parentaccount');
            // 是否禁用
            $data['isDisable'] = 2;

            // 是否删除
            $data['isDelete'] = 2;

            // 创建时间
            $data['createTime'] = now_datetime();

            // 更新时间
            $data['updateTime'] = now_datetime();
            //创建数据
            $result = M('member')->add($data);
            if ($result) {
                $this->ajaxSuccess("添加成功！");
            } else {
                $this->ajaxError("添加失败！");
            }
        } else {
            $this->display();
        }
    }

    // 编辑资料
    public function edit()
    {
        if (IS_POST) {
            // ID
            $id = I("post.id");

            // 没有ID
            if (empty($id)) {
                $this->ajaxError("错误！");
            }

            // 判断用户是否存在
            $dbData = M('member')
                ->where(array("id", $id))
                ->find();

            //判断用户是否存在
            if (empty($dbData)) {
                $this->ajaxError("数据不存在！");
            }

            // 更新数据
            $data = array();

            // 更新时间
            $data['updateTime'] = now();

            // 姓名
            $data['realName'] = trim(I('post.realName'));

            // 输入密码
            if (I('post.password') && I('post.password') != "") {
                // 密码
                $data['password'] = md5(trim(I('post.password')));
            }

            //身份证号
            if (I('post.idCard') && I('post.idCard') != "") {
                $data['idCard'] = trim(I('post.idCard'));
            }

            // 如果输入推荐人
            $parentaccount = I('post.parentaccount');
            if(!empty($parentaccount))
            {
                $parent = M('member')->where(array('account' => $parentaccount))->find();
                if ($parent) {
                    // 推荐人
                    $data['parentId'] = $parent['id'];
                    // 推荐人账户
                    $data['parentAccount'] = $parentaccount;
                } else {
                    $this->ajaxError("推荐人不存在！");
                }
            }else{
                // 推荐人
                $data['parentId'] = "";
                // 推荐人账户
                $data['parentAccount'] = "";
            }

            // 更新数据
            $result = M('member')
                ->where(array("id" => $id))
                ->save($data);

            if ($result !== false) {
                $this->ajaxSuccess("更新成功！");
            } else {
                $this->ajaxError("更新失败！");
            }
        } else {
            // ID
            $id = intval(I("get.id"));

            // 判断是否存在
            $data = M('member')
                ->alias("t")
                ->where(array("t.id" => $id))
                ->find();

            // 判断是否存在
            if (empty($data)) {
                $this->error("数据不存在");
            }
            $this->assign('lists', array(
                "isdisable" => getDropdownList("isDisable"),
                "isdelete" => getDropdownList("isDelete")
            ));

            $this->assign("data", $data);
            $this->display();
        }
    }

    // 删除
    public function delete()
    {
        if (IS_POST) {
            // ID
            $id = intval(I("post.id"));

            // 没有ID
            if (empty($id)) {
                $this->ajaxError("错误！");
            }

            //删除数据
            $result = M('member')->where(array("id" => $id))->save(array("isDelete" => 1));

            // 如果删除成功
            if ($result) {
                $this->ajaxSuccess("删除成功！");
            } else {
                $this->ajaxError("删除失败！");
            }
        }
    }

    // 禁用
    public function disable()
    {
        if (IS_AJAX) {
            // ID
            $id = intval(I("post.id"));

            // 没有ID
            if (empty($id)) {
                $this->ajaxError("错误！");
            }

            // flag
            $data['isDisable'] = "1";

            // 更新时间
            $data['updateTime'] = now_datetime();

            // 更新人
            $data['updateId'] = $this->getAccountId();

            // 更新数据
            $result = M('Member')->where(array("id" => $id))->save($data);

            // 如果成功
            if ($result) {
                $this->ajaxSuccess("禁用成功！");
            } else {
                $this->ajaxError("禁用失败！");
            }
        }
    }

    // 启用
    public function enable()
    {
        if (IS_AJAX) {
            // ID
            $id = intval(I("post.id"));

            // 没有ID
            if (empty($id)) {
                $this->ajaxError("错误！");
            }

            // flag
            $data['isDisable'] = "2";

            // 更新时间
            $data['updateTime'] = now_datetime();

            // 更新人
            $data['updateId'] = $this->getAccountId();

            // 更新数据
            $result = M('Member')->where(array("id" => $id))->save($data);

            // 如果成功
            if ($result) {
                $this->ajaxSuccess("启用成功！");
            } else {
                $this->ajaxError("启用失败！");
            }
        }
    }

    /**
     * 个人资料审核
     */
    public function dataReview()
    {
        if (IS_POST) {
            $uid = (int)I('post.id');

            $realName = trim(I('post.realname')); //真实姓名
            $idCard = trim(I('post.idcard')); //身份证号
            $idCardFrontImg = trim(I('post.idcardfrontimg')); //身份证正面
            $idCardBackImg = trim(I('post.idcardbackimg')); //身份证反面
            $idCardHold = trim(I('post.idcardhold')); //身份证手持
            $identityChk = (int)I('post.identitychk'); //审核状态

            if (empty($realName)) $this->ajaxError("请填写真实姓名！");
            if (empty($idCard)) $this->ajaxError("请填写身份证号！");
            if (!isIdentityCard($idCard)) $this->ajaxError("身份证号格式错误！");
            if (empty($idCardFrontImg)) $this->ajaxError("请上传身份证正面照！");
            if (empty($idCardBackImg)) $this->ajaxError("请上传身份证反面照！");
            if (empty($idCardHold)) $this->ajaxError("请上传身份证手持照！");
            if (empty($identityChk)) $this->ajaxError("请选择审核状态！");

            $res = M('member')->where(array("id"=>$uid))->save(array(
                "realName" => $realName,
                "idCard" => $idCard,
                "idCardFrontImg" => $idCardFrontImg,
                "idCardBackImg" => $idCardBackImg,
                "idCardHold" => $idCardHold,
                "identityChk" => $identityChk,
            ));

            if (false !== $res) {
                $this->ajaxSuccess("操作成功！");
            } else {

                $this->ajaxError("操作失败！");
            }

        } else {
            $uid = (int)I('get.id');
            $info = M("member")->where(array("id"=>$uid))->find();
            // 判断是否存在
            if (empty($info)) {
                $this->error("数据不存在");
            }

            $this->assign(array(
                "data" => $info,
            ));
            $this->assign("lists", array(
                "identitychk" => array(
                    1 => getDropdownList("identityChk", '1', false),
//                    2 => getDropdownList("identityChk", '2', false),
                    3 => getDropdownList("identityChk", '3', false),
                )
            ));
            $this->display("dataReview");
        }

    }

    /**
     * 后台添加用户
     */
    public function addNewUser()
    {
        if (IS_POST) {
            // 数据
            $data = array();
            // 姓名
            $data['nickname'] = I('post.nickname');
            // 账号
            $account= I('post.account');
            if (empty($account) || !isPhone($account)){
                $this->ajaxError("请填写正确格式的手机号！");
            }
            $member=M("member")->where(array("account"=>$account))->find();
            if(!empty($member)){
                $this->ajaxError("账号已存在！");
            }
            $parentaccount=I('post.parentaccount');
            if(empty($parentaccount)){
                $this->ajaxError("推荐人不能为空！");
            }
            $parent=M("member")->where(array("account"=>I('post.parentaccount')))->find();
            if(empty($parent)){
                $this->ajaxError("推荐人不存在！");
            }
            $wallet=I('post.wallet');
            $walletCount=M("member")->where(array("wallet"=>$wallet))->select();
            if(!empty($walletCount)){
                $this->ajaxError("钱包地址已存在，请更换钱包地址！");
            }
            $data['account']=$account;
            if (I('post.password') && I('post.password') != "") {
                // 密码
                $data['password'] = md5(trim(I('post.password')));
            }
            if (I('post.paypassword') && I('post.paypassword') != "") {
                // 支付密码
                $data['paypassword'] = md5(trim(I('post.paypassword')));
            }
            $data['parentId'] = $parent['id'];
            // 推荐人账户
            $data['parentAccount'] = I('post.parentaccount');
            // 是否禁用
            $data['isDisable'] = 2;
            // 是否删除
            $data['isDelete'] = 2;
            // 创建时间
            $data['createTime'] = now_datetime();
            // 更新时间
            $data['updateTime'] = now_datetime();
            //创建数据
            M()->startTrans();
            $result = M('member')->add($data);
            if(empty($result)){
                M()->rollback();
                $this->ajaxError("添加失败！");
            }
            $mem_save=M("member")->where(array("id"=>$result))->save(array("invitecode"=>$result));
            if(empty($mem_save)){
                M()->rollback();
                $this->ajaxError("添加失败！");
            }
            $data2['account'] = $account;
            $data2['userId'] = $result;
            $data2["createTime"] = date("Y-m-d H:i:s");
            $data2["updateTime"] = date("Y-m-d H:i:s");
            $result2 = M("virtualcurrency")->add($data2);

            if ($result2) {
                M()->commit();
                $this->ajaxSuccess("添加成功！");
            } else {
                M()->rollback();
                $this->ajaxError("添加失败！");
            }
        } else {
            $this->display();
        }
    }

    /**
     * 后台添加用户
     */
    public function sendMessage()
    {
        if (IS_POST) {
            $id = I("post.id");
            // 没有ID
            if (empty($id)) {
                $this->ajaxError("错误！");
            }

            // 判断用户是否存在
            $member = M('member')
                ->where(array("id", $id))
                ->find();

            //判断用户是否存在
            if (empty($member)) {
                $this->ajaxError("数据不存在！");
            }
            $title=I("post.title");
            $content=I("post.content");
            // 添加数据
            $data = array(
                "toUser"=>$id,
                "title"=>$title,
                "content"=>$content,
                "createTime"=>now_datetime(),
                "updateTime"=>now_datetime()
            );
            $result=M("notice")->add($data);
            if($result){
                $this->ajaxSuccess("发送成功");
            }else{
                $this->ajaxError("发送失败");
            }
        } else {
            $id = intval(I("get.id"));
            // 判断是否存在
            $data = M('member')
                ->alias("t")
                ->where(array("t.id" => $id))
                ->find();
            // 判断是否存在
            if (empty($data)) {
                $this->error("数据不存在");
            }
            $this->assign("data", $data);
            $this->display();
        }
    }

    /**
     * 修改积分和金额
     */
    public function updateBalanceIntegral(){
        if(IS_POST){
            $balance=I("balance");
            $uid = (int)I('id');
            $integral=I("integral");
            if(empty($uid)){
                $this->ajaxError("不能为空！");
            }
            $info = M("member")->where(array("id"=>$uid))->find();
            if(empty($info)){
                $this->ajaxError("用户不存在");
            }
            if(($info['balance']+$balance)<0 || ($info['integral']+$integral)<0){
                $this->ajaxError("用户余额或积分不足！");
            }
            M()->startTrans();
            $res=M("member")->where(array("id"=>$info['id']))->save(array("balance"=>($info['balance']+$balance),"integral"=>($info['integral']+$integral)));
            if($balance==0){
                $save_log=1;//如果只添加积分，余额变更为0则不添加log
            }else{
                $save_log = balancelog($res, $info['id'],$balance, $type=16, $before=$info['balance'], $after=$info['balance']+$balance);
            }
            if($integral==0){
                $integrallog=1;//如果只添加余额，积分变更为0则不添加log
            }else{
                $integrallog=integrallog($res, $info['id'],$integral,5,$info['integral'],($info['integral']+$integral));//转出积分log
            }
            if(empty($res) || empty($save_log) || empty($integrallog)){
                M()->rollback();
                $this->ajaxError("更改用户余额积分错误！");
            }
            M()->commit();
            $this->ajaxSuccess("成功");
        }else{
            $uid = (int)I('get.id');
            $info = M("member")->where(array("id"=>$uid))->find();
            $this->assign("data",$info);
            $this->display();
        }
    }
}